use std::collections::HashMap;
use std::sync::{Arc, RwLock};

use lazy_static::lazy_static;
use log::{error, info, warn};
use teloxide::prelude::*;
use teloxide::Bot;
use tokio::fs;

use crate::commands::{answer, Command};
use crate::services::http::make_http_server;
use crate::structs::bs_user::BSUser;
use crate::structs::pager_number::PagerNumbers;

mod bot;
mod http;
mod telegram;

lazy_static! {
    pub static ref NUMBERS: Arc<RwLock<PagerNumbers>> = {
        let n = PagerNumbers {
            items: HashMap::new(),
        };

        Arc::new(RwLock::new(n))
    };
}

async fn load_numbers() -> PagerNumbers {
    let path = "data.json";
    let data = fs::read_to_string(path).await.expect("Unable to read file");
    let res: PagerNumbers = serde_json::from_str(&data).expect("Unable to parse");
    info!("{:?}", res);
    res
}

pub fn start_numbers_loop() {
    warn!("{}", NUMBERS.read().unwrap().dumb());
    tokio::spawn(async {
        info!("Starting Subscribers Sync...");
        loop {
            let pg = load_numbers().await;
            {
                let mut r = NUMBERS.write().unwrap();
                r.items = pg.items;
            }
            tokio::time::sleep(tokio::time::Duration::from_secs(10)).await
        }
    });
}

pub fn start_tgbot() {
    let bot = Bot::from_env();
    info!("Starting Bot...");
    tokio::spawn(async { Command::repl(bot, answer).await });
}

pub async fn start_http() {
    info!("Starting HTTP Server...");
    make_http_server().await;
}

pub async fn start_bsbot() {
    start_numbers_loop();
    start_tgbot();
    start_http().await
}

pub fn create_user(name: String) {
    let password = rpassword::prompt_password("Your password: ").unwrap();
    let usr = BSUser::create(&name, &password);
    match usr {
        Ok(v) => {
            info!("User {} created", v.username)
        }
        Err(e) => {
            error!("Error {}", e)
        }
    }
}
